package indi.bookmarkx.utils;

import indi.bookmarkx.model.AbstractTreeNodeModel;
import org.apache.commons.lang3.StringUtils;

import java.io.*;

public class BookMarkFileUtil {

    /**
     * 将书签的描述转换成markdown文件
     */
    public  static String  convertToMarkdown(AbstractTreeNodeModel nodeModel, String projectDir) {
        if( null == nodeModel ) {
            return "";
        }
        String name = nodeModel.getName();

        // 没有名字，不生成 md 文件
        if(StringUtils.isEmpty(name)) {
            return "";
        }
        name = name.strip(); // 去处空格

        // 路径不存在则创建路径
        String filePath = projectDir + "/.idea/bookmark_md/" ;
        File folder = new File(filePath);
        if (!folder.exists()) {
            if (folder.mkdirs()) {
                System.out.println("Folder created successfully!");
            } else {
                System.out.println("Failed to create folder!");
            }
        } else {
            System.out.println("Folder already exists!");
        }

        // 文件不存在则创建文件
        String fileName = name + ".md";

        // 创建File对象
        File file = new File(filePath + fileName);

        try {
            // 如果文件不存在，则创建文件
            if (!file.exists()) {
                boolean fileCreated = file.createNewFile();
                if (fileCreated) {
                    System.out.println("文件创建成功：" + filePath);
                } else {
                    System.out.println("文件创建失败：" + filePath);
                }
            } else {
                System.out.println("文件已存在：" + filePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }




        String desc = nodeModel.getDesc();

        try {
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath + fileName), "UTF-8"));
//            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath + fileName), "GBK"));
//            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath + fileName ));
            bufferedWriter.write(desc);
            bufferedWriter.flush();
            bufferedWriter.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return filePath + fileName;

    }
}
